//
//  LLGUserAccountViewModel.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/10.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit

//封装OAuth网络请求接口,对应控制器LLGOAuthViewController
class LLGUserAccountViewModel: NSObject {

    static let sharedUserAccount: LLGUserAccountViewModel = LLGUserAccountViewModel()
    
    // MARK: --获取用户信息
    var userAccount: LLGUserAccount? {
    
        return LLGUserAccount.loadUserAccount()
    }
    
    // MARK: --判断是否登录
    var isLogin: Bool {
    
        return accessToken != nil
    }
    
    // MARK: --获取accessToken,并判断是否过去
    var accessToken: String? {
    
        guard let token = userAccount?.access_token else {
        
            return nil
        }
        
        let result = userAccount?.expiresDate?.compare(NSDate())
        
        //降序
        if result == NSComparisonResult.OrderedDescending {
        
            return token
        } else {
            return nil
        }
    }
    
    // MARK: --获取AccessToken
    func requestAccessToken(code: String, callBack: (isSuccess: Bool) -> ()) {
        
        LLGNetworkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
            
            if error != nil {
                callBack(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String : AnyObject] else {
                callBack(isSuccess: false)
                return
            }
            
            let userAccount: LLGUserAccount = LLGUserAccount(dict: dict)
            
            self.requestUserInfo(userAccount, callBack: callBack)
        }
        
    }
    
    // MARK: --获取UserInfo
    private func requestUserInfo(userAccount: LLGUserAccount, callBack: (isSuccess: Bool) -> ()) {
        
        
        LLGNetworkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
            
            if error != nil {
                
                callBack(isSuccess: false)
                return
            }
            
            guard let dict = response as? [String: AnyObject] else {
                
                callBack(isSuccess: false)
                return
            }
            
            userAccount.name = dict["name"] as? String
            userAccount.avatar_large = dict["avatar_large"] as? String
            
            userAccount.saveUserAccount()
            
            callBack(isSuccess: true)
        }
        
        
    }
    
}
